<?php
if ( empty($_COOKIE['user']) )
	header('Location: login.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>iGeoTrack</title>
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/>
<link rel="apple-touch-icon" href="./icon.png" />
<meta name="apple-touch-fullscreen" content="YES" />
<style type="text/css" media="screen">@import "./chat/chat.css";</style>
<style type="text/css" media="screen">@import "./iui/iui.css";</style>
<style type="text/css">
body > .panelmap {
    box-sizing: border-box;
    -webkit-box-sizing: border-box;
    background: #c8c8c8 url(pinstripes.png);
}

div.loading {
	display: none;
}

.itable					{ border: 1px solid gray; }
.itable tr.header th	{ text-align: left; }
.itable tr.alt			{ background-color: #eff7ff; }
.itable tr.reg			{ background-color: #fff; }
.itable th				{ background: url(/iui/blue_hd_bg.png) top left repeat-x; border-right: 1px solid grey; }
.itable th:last-child	{ border-right: none; }
.itable td				{ border-right: 1px solid gray; }
.itable tr:first-child	{ white-space: nowrap; }
.itable tr:last-child	{ border-right: none; }

A.dialogLink:link {text-decoration: none; color: #CCCCCC;}
A.dialogLink:visited {text-decoration: none; color: #CCCCCC;}
A.dialogLink:active {text-decoration: none; color: #CCCCCC;}
A.dialogLink:hover {text-decoration: underline; color: #CCCCCC;}
</style>
<!--<script type="text/javascript" src="http://www.google.com/jsapi?key=<?=MAPS_API_KEY?>"></script>-->
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="application/x-javascript" src="./iui/iui.js"></script>
<script type="text/javascript" src="./fleegix.js"></script>
<script type="text/javascript" src="./inspect.js"></script>
<script type="text/javascript" src="./map.js"></script>
<script type="text/javascript" src="./xml.js"></script>
<script type="text/javascript">
	/**
	 * Global variables.
	 */
	var user;							// a string representing the active user
	var users;							// an array object containing the nearby users
	var theMap;							// a custom maps object
	var isReloadNecessary;				// true if's time to reload the (nearby users) data, else false
	var chatUpdates;					// true if constant chat updates are needed, else false
	
	/**
	 * Loads client.
	 */
	function initialize()
	{
		// set global variables
		user = "<?=$_COOKIE['user']?>";
		isReloadNecessary = false;
		
		// load map object (with default coordinates [in Leuven])
		theMap = new Map(document.getElementById("theMap"), 50.875, 4.690);
		
		// try to request the GPS coordinates and set if possible (else: show error message)
		findLocation();
		
		// orientation
		getOrientationString();
	}
	
	/**
	 * If the (nearby users) data is old -> a reload is necessary.
	 * Otherwise, we can wait for 30 seconds
	 */
	function setReloadNecessary(necessary)
	{
		if (necessary) {
			isReloadNecessary = true;
		} else {
			isReloadNecessary = false;
			setTimeout("setReloadNecessary(true)", 30000); // reload not necessary for 30s
		}
	}
	
	/**
	 * Called when "menu" is loaded.
	 * This function checks if a reload of the data is necessary.
	 * It is only necessary if the last update was > 30 seconds ago or if the settings have been changed.
	 */
	function checkReload()
	{
		if (isReloadNecessary)
			findLocation();
	}
	
	/**
	 * Orientation.
	 */
	function getOrientationString()
	{
		switch(window.orientation)
	   	{
			case 0:
				e=document.getElementById("theMap");
				e.style.width = 320 + 'px';
				e.style.height = 370 + 'px';
			break;
			case -90:
				e=document.getElementById("theMap");
				e.style.width = 480 + 'px';
				e.style.height = 215 + 'px';         
			break;
			case 90:
				e=document.getElementById("theMap");
				e.style.width = 480 + 'px';
				e.style.height = 215 + 'px';
			break;
			case 180:
				e=document.getElementById("theMap");
				e.style.width = 320 + 'px';
				e.style.height = 370 + 'px';
			break;               
			default:
				e=document.getElementById("theMap");
				e.style.width = 320 + 'px';
				e.style.height = 370 + 'px';
			break;
		}
	}
	
	/**
	 * Shows a "loading" message and blocks the menu.
	 */
	function toggleLoading(msg) {
		document.getElementById("loadingMessage").innerHTML = msg;
		var loadingDiv = document.getElementById("loading");
		loadingDiv.style.display = loadingDiv.style.display == "block" ? "none" : "block";
		toggleDisabled(document.getElementById("menu"));
	}
	
	/**
	 * Disables/enables all elements in a div.
	 */
	function toggleDisabled(el)
	{
		try {
			el.disabled = el.disabled ? false : true;
		}
		catch(E){}
		
		if (el.childNodes && el.childNodes.length > 0) {
			for (var x = 0; x < el.childNodes.length; x++) {
				toggleDisabled(el.childNodes[x]);
			}
		}
	}
		
	/**
	 * Find GPS coordinates.
	 */
	function findLocation()
	{
		toggleLoading("Loading nearby users..");
		if (navigator.geolocation) {
			navigator.geolocation.getCurrentPosition(foundLocation, noLocation);
		} else {
			alert('Navigator not supported!');
			//iui.showPage(document.getElementById('menu'), document.getElementById('login'));
		}
	}
	
	/**
	 * The device has found GPS coordinates.
	 */
	function foundLocation(position)
	{
		// load coordinates
		inspect(position, 3);
		theMap.currentLatitude = position.coords.latitude;
		theMap.currentLongitude = position.coords.longitude;
		
		// load users array
		loadUsers();
		
		// fresh data!
		setReloadNecessary(false);
		
		// disable loading message
		toggleLoading("");
	}
	
	/**
	 * The browser does not support this function.
	 */
	function noLocation(error)
	{
		switch (error.code) {
			case error.PERMISSION_DENIED:
				alert('Sorry. Permission to find your location has been denied.');
				break;
			case error.POSITION_UNAVAILABLE:
				alert('Sorry. Position unavailable.');
				break;
			default:
				alert('Error ' + error.code);
		}
		
		// fresh data!
		setReloadNecessary(false);
		
		// disable loading message
		toggleLoading("");
	}
	
	/**
	 * Loads an array of nearby users into the "user details" page.
	 */
	function loadUsers()
	{
		// build url for the dynamic xml file
		var url = 'geo_users.php?user=' + user + '&lat=' + theMap.currentLatitude + '&lon=' + theMap.currentLongitude;
		
		// check if "age" setting is set
		if ( document.getElementById("settingsAge").value ) {
			url += '&max_age=' + document.getElementById("settingsAge").value
		}
		
		// check if "distance" setting is set
		if ( document.getElementById("settingsDistance").value ) {
			url += '&max_distance=' + document.getElementById("settingsDistance").value
		}
		
		// check if "score" setting is set
		if ( document.getElementById("settingsScore").value ) {
			url += '&min_score=' + document.getElementById("settingsScore").value
		}
		
		// request xml
		var resp = fleegix.xhr.get(url, 'xml');
		
		// parse xml
		users = fleegix.xml.parse(resp, 'User').User;
		
		// small "hack" to check if the response is a User object instead of an array
		if(users && users.Score) {
			newUsers = new Array(1);
			newUsers[0] = clone(users);
			users = newUsers;
		}
	}
	
	/**
	 * Clones objects.
	 */
	function clone(obj)
	{
		if(obj == null || typeof(obj) != 'object')
			return obj;
		var temp = new obj.constructor(); // changed (twice)
		for(var key in obj)
			temp[key] = clone(obj[key]);
		return temp;
	}
	
	/**
	 * Returns a function pointer to loadUser (necessary for the id argument!).
	 */
	function newLoadUserHandler(id) 
	{
		return function() {
			loadUser(id);
        };
	}
	
	/**
	 * Loads the details view of a user.
	 */
	function loadUser(id)
	{
		if ( id >= 0 && id < users.length )
		{
			users[id].Thumbnail_large = users[id].Thumbnail_large && users[id].Thumbnail_large != "" ? users[id].Thumbnail_large : "unknown.png";
			document.getElementById('userName').innerHTML = users[id].Name;
			document.getElementById('userImage').src = users[id].Thumbnail_large;
			document.getElementById('userDistance').value = users[id].Distance + " km away";
			document.getElementById('userTime').value = users[id].Age + " minutes ago";
			document.getElementById('userScore').value = users[id].Score + "% related";
			
			iui.showPage(document.getElementById('userdetails'), document.getElementById('mapdiv'));
		} 
		else
		{
			alert("Invalid user (id " + id + "!");
		}
	}
	
	/**
	 * Loads the chat messages.
	 */
	function loadChat()
	{
		// show loading message
		toggleLoading("Loading chat..");
		
		// build url for the dynamic xml file
		var to = document.getElementById("userName").innerHTML;
		var url = 'chat/check_chat.php?user1=' + user + '&user2=' + to;
		
		// request xml
		var resp = fleegix.xhr.get(url, 'xml');
		
		// parse xml
		var messages = fleegix.xml.parse(resp, 'Message').Message;
		var msgWall = '';
		
		if(messages) {
		
			// small "hack" to check if the response is a Message object instead of an array
			if(messages.User) {
				newMessages = new Array(1);
				newMessages[0] = clone(messages);
				messages = newMessages;
			}
			
			// write messages
			for ( i in messages ) {
				
				// left or right bubble?
				if ( i%2 == 0 )
					msgWall += '<div class="bubble left">';
				else
					msgWall += '<div class="bubble right">';
					
				// colour depends on sender
				if ( messages[i].User.toLowerCase() == user.toLowerCase() )
					msgWall += '<p class="graphite">';
				else
					msgWall += '<p class="aqua">';
					
				// write message
				msgWall += messages[i].Text + '</p>';
				msgWall += '</div>';
				
				// write time & sender name
				msgWall += '<p>' + messages[i].Time + ' - ' + messages[i].User + '</p>';
				
			}
			
		}
		
		// load page
		document.getElementById('chattingWith').innerHTML = 'Chatting with ' + to;
		document.getElementById('from').value = user;
		document.getElementById('to').value = to;
		document.getElementById('chat').innerHTML = msgWall;
		
		// disable loading message
		toggleLoading("");
	}
	
	/**
	 * Set constant chat updates on/off.
	 */
	function setChatUpdates(updates)
	{
		if (updates) {
			chatUpdates = true;
			setTimeout("doChatUpdate()", 3000);
		} else {
			chatUpdates = false;
		}
	}
	
	/**
	 * Update chat.
	 */
	function doChatUpdate()
	{
		if (chatUpdates) {
			loadChat();
			setTimeout("doChatUpdate()", 3000);
		}
	}
	
	/**
	 * Creates a list of nearby users (as a table).
	 */
	function writeUserTable()
	{
		if (users)
		{
			var table = '<tr class="header"><th>User</th><th>Distance</th><th class="last">Last Updated</th></tr>';
			
			for ( i in users ) {
				if (i%2 == 0)
					table += '<tr class="reg" ';
				else
					table += '<tr class="alt" ';
					
				table += 'onclick="loadUser(' + i + ');">';
					
				table += '<td class="first">' + users[i].Name + '</td>';
				table += '<td>' + users[i].Distance + ' km</td>';
				table += '<td class="last">' + users[i].Age + '\' ago</td>';
			
				table += '</tr>';
			}
			
			document.getElementById("userTable").innerHTML = table;
		}
		else
		{
			document.getElementById("userTable").innerHTML = '<tr class="header"><th>User</th><th>Distance</th><th class="last">Last Updated</th></tr>';
		}
	}
	
	/**
	 * Creates a list of artist matches.
	 */
	function writeArtistList()
	{
		var otherUser = document.getElementById("userName").innerHTML;
		
		if (otherUser)
		{
			// build url for dynamic xml file
			var url = 'related_artists.php?user1=' + user + '&user2=' + otherUser;
			
			// load xml
			var resp = fleegix.xhr.get(url, 'xml');
			
			// parse xml
			var artists = fleegix.xml.parse(resp, 'Artist').Artist;
			
			// write list
			var list = '';
			for ( i in artists ) {
				list += '<li><a href=' + artists[i].Url + ' target="_self">';
				list += artists[i].Name + '</a></li>';
			}
			document.getElementById("artistlist").innerHTML = list;
		}
	}
</script>
</head>

<body onload="initialize();" onunload="getOrientationString();" onresize="getOrientationString();" onorientationchange="getOrientationString();">

    <div class="toolbar">
        <h1 id="pageTitle">iGeoTrack</h1>
        <a id="backButton" class="button" href="#" onclick="setChatUpdates(false);"></a>
    </div>
    
    <div id="loading" class="dialog">
    	<p id="loadingMessage" style="text-align: center; color: #FFFFFF; font-weight: bold; padding: 50px;">Loading nearby users..</p>
   	</div>
   
    <ul id="menu" title="Menu" selected="true" onfocus="checkReload();">
        <li><a href="#mapdiv">Map</a></li>
        <li><a href="#userlist" onclick="writeUserTable();">User list</a></li>
        <li><a href="#settings">Settings</a></li>
        <li><a href="#about">About</a></li>
        <li><a href="logout.php" target="_self">Log out</a></li>
    </ul>

    <div id="mapdiv" title="Map" class="panelmap">
        <div id="theMap"></div>
    </div>
	
	<div id="userdetails" title="User" class="panel">
        <h2 id="userName"></h2>
        <fieldset>
            <div class="row" style="text-align: center;">
                <img name="userImage" id="userImage" src="unknown.png" align="middle" style="padding: 10px;">
            </div>
            <div class="row">
                <label>Distance</label>
                <input type="text" name="userDistance" id="userDistance" />
            </div>
            <div class="row">
                <label>Last Update</label>
                <input type="text" name="userTime" id="userTime" />
            </div>
            <div class="row">
                <label>Score</label>
                <input type="text" name="userScore" id="userScore" />
            </div> 
        </fieldset>
        <a href="#artistlist" class="whiteButton" onclick="writeArtistList();">Favourite artists matches</a><br />
        <a href="#chatPanel" class="whiteButton" onclick="setChatUpdates(true);">Chat with this user!</a>
    </div>
    
    <form id="chatPanel" title="Chat" class="panel" method="post" action="chat/send_message.php">
        <h2 id='chattingWith'>Chatting with x</h2>
        <input type="hidden" id="from" name="from" value="" />
        <input type="hidden" id="to" name="to" value="" />    
        <fieldset>
            <div class="row">
           		<label>Message</label>
                <input type="text" name="message" value=""/>
            </div>
        </fieldset>
        <a class="whiteButton" type="submit" href="#">Send</a>
        <div id="chat">
        </div>
    </form>
    
    <div id="userlist" title="Nearby users" class="panel">
    	<table class="itable" id="userTable" width="100%" border="0" cellspacing="0" cellpadding="3">
        	<tr class="header">
            	<th>User</th>
                <th>Distance</th>
                <th class="last">Last Updated</th>
           	</tr>
		</table>
    </div>
    
    <ul id="artistlist" title="Artist matches">
    </ul>
   
    <div id="settings" title="Settings" class="panel">
    	<h2>Nearby users</h2>
        <fieldset>
            <div class="row">
                <label>&quot;Age&quot;</label>
                <input type="text" id="settingsAge" value="30" onchange="setReloadNecessary(true);" />
            </div>
            <div class="row">
                <label>Distance</label>
                <input type="text" id="settingsDistance" value="10" onchange="setReloadNecessary(true);" />
            </div>
            <div class="row">
                <label>Score</label>
                <input type="text" id="settingsScore" value="0.3" onchange="setReloadNecessary(true);" />
            </div>
        </fieldset>
        
    	<h2>Map</h2>
        <fieldset>
            <div class="row">
                <label>&quot;Current user&quot; marker</label>
                <div id="showCurrentUserMarker" class="toggle" toggled="true" onclick="theMap.changeShowCurrentUserMarker();"><span class="thumb"></span><span class="toggleOn">ON</span><span class="toggleOff">OFF</span></div>
            </div>
        </fieldset>
    </div>
    
    <div id="about" title="About" class="dialog">
    	<p style="text-align:center; color:#FFFFFF; font-weight:bold; padding: 20px;">
			About iGeoTrack...<br /><br />
            iGeoTrack is an iPhone web application <br />made by Laurens Van Keer and Bram Truyaert.<br /><br />
            <a href="http://mumetech.wordpress.com/" target="_self" class="dialogLink">For more information, click here</a>
        </p>
   	</div>
	 
</body>
</html>